import React from 'react'
import { connect } from 'dva'
import { Form, Button, Modal, Popconfirm, Table, Row, Col, Input, Select, message, Icon, Checkbox, Radio, Tooltip, Tabs, Cascader, DatePicker } from 'antd'
import config from 'config/config'
import { mapStateToProps } from 'utils/view_utils'
import styles from './giftAddStyle.less'
import classnames from 'classnames/bind';
let cx = classnames.bind(styles);
import Uploader from 'widget/Upload'
import { isEmpty, isArray, cloneDeep, set, get, pick } from 'lodash'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import moment from 'moment';

// 引入列表页组件
// import Ueditor from '../../../../widget/Editor/Ueditor.js'
import Ueditor from '../../../../widget/Editor/Ueditor.js'
import ListPage from 'widget/PageTmpl/ListPage'

import giftDetail_demo from '../../../../assets/img/gift/giftDetail_demo.png'
import giftDetail_demo1 from '../../../../assets/img/gift/giftDetail_demo1.png'
import giftDetail_demo2 from '../../../../assets/img/gift/giftDetail_demo2.png'
import giftDetail_demo3 from '../../../../assets/img/gift/giftDetail_demo3.png'


const FormItem = Form.Item
// const TabPane = Tabs.TabPane
// const confirm = Modal.confirm;
const InputGroup = Input.Group;
const { RangePicker } = DatePicker
const Option = Select.Option


const formItemLayout = {
	labelCol: { span: 4 },
	wrapperCol: { span: 19 },
};
const formItemLayoutTime = {
	labelCol: { span: 5 },
	wrapperCol: { span: 19 },
};
const formItemLayout2 = {
	labelCol: { span: 2 },
	wrapperCol: { span: 8 },
};
const formItemLayoutForTime = {
	labelCol: { span: 2 },
	wrapperCol: { span: 20 },
};
const formItemLayout3 = {
	labelCol: { span: 8 },
	wrapperCol: { span: 16 },
}
const formItemLayout4 = {
	labelCol: { span: 4 },
	wrapperCol: { span: 20 },
}
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const giftAddView = function ({ dispatch, model, form }) {
	// 表单的子函数
	const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
	// 取出model对象，命名空间
	const { modelObj, namespace } = model
	let { currentStep, actionType, btnLoading, gif, detail, areaList, estateList, isShelfStatus, isSubmit, imgModal } = modelObj
	console.log(detail)
	function inputChange(value, type, index) {
		// console.log(e, type)
		if (type == 'areaId') {
			// console.log(value)
			detail.province = value[0]
			detail.city = value[1]
			// detail.parentProductId = ""
			dispatch({ type: `${namespace}/getHouseArea`, payload: { province: value[0], city: value[1] } })
		} else if (type == 'isSelfTemplate') {
			detail[type] = value

			if (detail[type] === true) {//
				detail.selfTemplateImg ? detail.bottomImg = detail.selfTemplateImg : detail.bottomImg = ""
			} else {
				detail.selfTemplateImg = detail.bottomImg
				detail.bottomImg = detail.bottomImg2
				detail.bottomImgId = detail.bottomImgId2
			}

			// console.log(detail)
		} else if (type == 'bottomImg') {
			detail[type] = value
			detail.bottomImg2 = value
			detail.bottomImgId = `gift-${index}`
			detail.bottomImgId2 = `gift-${index}`
		}
		else {
			detail[type] = value
		}

		changeState({ detail })

	}


	//封面图改变时
	function updateImageModel(value, type) {
		detail[type] = value
		changeState({ detail })
	}
	//日期改变时
	function dateChange(m, s, type) {
		console.log(m, s)
		if (type == 'onlineTime') {
			changeState({
				detail: {
					...detail,
					startOnlineTime: s[0],
					endOnlineTime: s[1],
				}
			})
		} else if (type == 'offlineTime') {
			changeState({
				detail: {
					...detail,
					startOfflineTime: s[0],
					endOfflineTime: s[1],
				}
			})
		}

	}
	//提交
	function submit() {
		validateFields((err, values) => {
			console.log(err)
			if (!err) {
				dispatch({
					type: `${namespace}/submit`,
					payload: {}
				})
			}
		});
	}

	function removeImgUrl(type) {
		detail[type] = ''
		form.resetFields(type)
		changeState({ detail })
	}
	//输入字数限制
	function capture(value, num) {
		// console.log(value,num)
		if (value) {
			value = value.substr(0, num)
		}
		return value
	}

	function changeImgModal(visible = false, srcs = []) {
		// console.log(imgModal)
		imgModal.visible = visible
		imgModal.srcs = srcs || modelObj.srcs
		changeState({ imgModal })
	}

	//修改状态
	const changeState = (payload) => {
		// console.log(payload);
		dispatch({
			type: `${namespace}/updateStore`,
			payload: { ...payload }
		})
	};


	return (
		<div className={cx('pageLayout')}>
			<div className='public_listMain'>
				<div className={"functionButton"}>
					{/* {actionType == "add" || actionType == "edit" ?
						<Button type='primary' onClick={e => submit()} loading={btnLoading}>提交</Button> : null} */}
					<Button type='primary' onClick={e => submit()} loading={btnLoading} disabled={!isSubmit}>提交</Button>
				</div>
				<Form>
					<div className="boxShadow">
						<CollapsiblePanels title='礼品入口配置' tooltip="注：当超出该楼盘所有礼品领取时间则该礼品入口关闭" hideUpDownBtn={true} showModal={(e) => { changeImgModal(e, [giftDetail_demo]) }}>
							<Row>
								<Col span={12}>
									<FormItem label='礼品推广名称'  {...formItemLayout}>
										{getFieldDecorator('spreadName', {
											rules: [{
												required: true, message: '方案最多14个字', max: 14
											}],
											initialValue: detail.spreadName,
										})(
											<Input placeholder="方案最多14个字" onChange={(e) => { inputChange(e.target.value, 'spreadName') }} />
										)}
									</FormItem>
								</Col>

							</Row>
							<Row>
								<Col style={{ paddingLeft: '10' }}>楼盘主页入口样式选择：</Col>
							</Row>
							<Row>
								<div style={{ "width": "100%" }}>
									<div className={cx('box')}>
										<FormItem >
											{getFieldDecorator('bottomImg', {
												initialValue: detail.bottomImg,
												rules: [
													{ required: false, whitespace: true, message: '请选择礼品图' },
												],
											})(
												<Radio.Group disabled={detail.isSelfTemplate === true} className={cx('radioLayout')}>
													{gif.map((item, index) => {
														return (
															<div className={cx('preview')} key={index}>
																<img className={cx('imgBg')} src={item} alt="礼品背景图" />
																<div className={cx('title')}>
																	{
																		capture(detail.spreadName, 14)
																	}
																</div>
																<div className={cx('center')}><Radio value={detail.isSelfTemplate === true ? '' : item} onChange={(e) => { inputChange(e.target.value, 'bottomImg', index) }}>选择</Radio></div>
															</div>
														)
													})}
													<div className={cx('preview')}>
														<Col span={8}>
															<FormItem {...formItemLayout} >
																<Uploader
																	uploadedUrls={detail.bottomImg}
																	removeFileCbf={() => { removeImgUrl('bottomImg') }}
																	uploadSuccessCbf={(imgUrl) => {
																		updateImageModel(imgUrl, 'bottomImg')
																	}}
																	showType={detail.isSelfTemplate === false ? '' : "6"}
																	// showType='3'
																	minCropBoxWidth={343}
																	minCropBoxHeight={90}
																	unsetWidth={true}
																	fileType='image'
																	fileMaxSize='0.2'
																	maxFiles='1'
																/>
															</FormItem>
														</Col>
														<Col span={16}><span>{detail.isSelfTemplate === false ? '' : '图片分辨率需为343px*90px，且文件大小在200kb以下，支持jpg，png格式。'}</span></Col>
														<Checkbox checked={detail.isSelfTemplate} onChange={e => { inputChange(e.target.checked, 'isSelfTemplate') }} style={{ 'marginTop': '10px' }}>选择自定义配置图</Checkbox>
													</div>
												</Radio.Group>
											)}
										</FormItem>

									</div>
								</div>
							</Row>

						</CollapsiblePanels>

						<CollapsiblePanels title={'礼品规则配置'} hideUpDownBtn={true}>
							<Row>
								<Col span={12}>
									<FormItem
										{...formItemLayout4}
										extra="图片分辨率需为750px*560px，且文件大小在500kb以下，支持jpg，png格式。"
										label="礼品封面图"
										required={true}
									>
										{getFieldDecorator('giftCoverImg',{
											rules:[{
												required:true,
												message:'请选择礼品封面图'
												}],
												initialValue:detail.giftCoverImg
												})(
													<div className={cx('uploaderBox')}>
														<div className={cx('uploaderDiv')}>
															<Uploader
																uploadedUrls={detail.giftCoverImg}
																removeFileCbf={() => { removeImgUrl('giftCoverImg') }}
																uploadSuccessCbf={(imgUrl) => {
																	updateImageModel(imgUrl, 'giftCoverImg')
																}}
																// showType={actionType == 'detail'?'4':"3"}
																showType='6'
																minCropBoxWidth={750}
																minCropBoxHeight={560}
																// unsetWidth={true}
																fileType='image'
																fileMaxSize='0.5'
																maxFiles='1'
															/>
														</div>
														<div className={cx('tipBox')}>
															<Icon type="question-circle" className={'mgr1'} style={{ color: '#08c' }} />
															<a href="javascript:void(0)" onClick={() => { changeImgModal(true, [giftDetail_demo3]) }}>封面图显示在哪里?</a>
														</div>
													</div>
												)}
									</FormItem>
								</Col>
								
							</Row>
							{/* <Row><Col span={2}></Col><Col style={{ color: '#999', marginBottom: '20px' }}>图片分辨率需为750px*560px，且文件大小在200kb以下，支持jpg，png格式。</Col></Row> */}
							<Row style={{ marginBottom: '20' }}>
								<Col span={2}></Col>
								<Col>
									<Checkbox checked={detail.isPublishHouse} onChange={e => { inputChange(e.target.checked, 'isPublishHouse') }}>是否同步发布到福利页面</Checkbox>
									<Tooltip title="注：勾选后将会同步显示到美的置业云福利栏目中。">
										<Icon type="question-circle" className={cx('iconTip')} />
									</Tooltip>
								</Col>
							</Row>
							<Row>
								{detail.isPublishHouse &&
									(
										<div>
											<Col span={12}>
												<FormItem
													{...formItemLayout4}
													extra="图片分辨率需为1372px*672px，且文件大小在500kb以下，支持jpg，png格式。"
													label="首页活动封面图"
													required={true}
												>
													{getFieldDecorator('activityCoverImg',{
														rules:[{
															required:true,
															message:'请选择首页活动封面图'
														}],
														initialValue:detail.activityCoverImg
													})(
														<div className={cx('uploaderBox')}>
															<div className={cx('uploaderDiv')}>
																<Uploader
																	uploadedUrls={detail.activityCoverImg}
																	removeFileCbf={() => { removeImgUrl('activityCoverImg') }}
																	uploadSuccessCbf={(imgUrl) => {
																		updateImageModel(imgUrl, 'activityCoverImg')
																	}}
																	// showType={actionType == 'detail'?'4':"3"}
																	showType='6'
																	minCropBoxWidth={1372}
																	minCropBoxHeight={672}
																	// unsetWidth={true}
																	fileType='image'
																	fileMaxSize='0.5'
																	maxFiles='1'
																/>
															</div>
															<div className={cx('tipBox')}>
																<Icon type="question-circle" className={'mgr1'} style={{ color: '#08c' }} />
																<a href="javascript:void(0)" onClick={() => { changeImgModal(true, [giftDetail_demo1]) }}>封面图显示在哪里?</a>

															</div>
														</div>
													)}
													

												</FormItem>
											</Col>
											<Col span={6}>

											</Col>
										</div>

									)

								}
							</Row>
							{/* {detail.isPublishHouse &&
								<Row><Col span={2}></Col><Col style={{ color: '#999', marginBottom: '20px' }}>图片分辨率需为1372px*672px，且文件大小在200kb以下，支持jpg，png格式。</Col></Row>
							} */}
							<Row>
								{detail.isPublishHouse &&
									<Col span={6}>
										<FormItem label='首页活动按钮'  {...formItemLayout3}>
											{getFieldDecorator('buttonName', {
												rules: [{
													required: true, message: '最多5个字', max: 5
												}],
												initialValue: detail.buttonName,
											})(
												<Input disabled={!detail.isPublishHouse} placeholder="如:立即申领，最多5个字" onChange={(e) => { inputChange(e.target.value, 'buttonName') }} />
											)}
										</FormItem>
									</Col>
								}
								{detail.isPublishHouse &&
									<Tooltip title="注：勾选后将会同步显示到美的置业云首页美房活动栏目中。">
										<Icon type="question-circle" className={cx('iconTip')} onClick={() => { changeImgModal(true, [giftDetail_demo2]) }} />
									</Tooltip>
								}
							</Row>

							<Row>
								<Col span={12}>
									<FormItem label='礼品名称'  {...formItemLayout}>
										{getFieldDecorator('title', {
											rules: [{
												required: true, whitespace: true, message: '请输入礼品名称'
											}],
											initialValue: detail.title ? detail.title + '' : undefined
										})(
											<Input
												// disabled={actionType == 'detail'}
												placeholder='请输入礼品名称' onChange={(e) => { inputChange(e.target.value, 'title') }} />
										)}
									</FormItem>
								</Col>
								<Col className="col" span={12}>
									<FormItem {...formItemLayout} label="所属项目">
										{getFieldDecorator('projectId', {
											initialValue: detail.projectId,
											rules: [
												{
													required: true, whitespace: true, message: '请输入所属项目',
													validator: (rule, value, callback) => {
														console.log(rule, value)
													}
												},
											],
										})(
											<InputGroup compact>
												<Cascader style={{ width: '50%' }}
													disabled={actionType != 'add'}
													options={areaList}
													value={[`${detail.province}`, `${detail.city}`]}
													onChange={(value, selectedOptions) => inputChange(value, "areaId")} placeholder="请选择所属城市" />
												<Select style={{ width: '50%' }} notFoundContent={'该省市中无楼盘'}
													disabled={actionType != 'add'} value={detail.projectId}
													onChange={(e) => inputChange(e, 'projectId')} placeholder="请选择项目">
													{
														estateList && estateList.map((item, index) => (
															<Select.Option key={`house_${index}`} value={item.productId}>{item.name}</Select.Option>
														))
													}
												</Select>
											</InputGroup>
										)}
									</FormItem>
								</Col>

							</Row>
							<Row>
								<Col span={12}>
									<FormItem label='总库存量'  {...formItemLayout}>
										{getFieldDecorator('totalStock', {
											rules: [
												{ required: true, whitespace: true, message: '请输入总库存量' },
												{ pattern: /^[1-9]\d*$/, message: '请输入数字' },
											],
											initialValue: detail.totalStock ? detail.totalStock + '' : undefined
										})(
											<Input
												// disabled={actionType == 'detail'}
												placeholder='请输入总库存量' onChange={(e) => { inputChange(e.target.value, 'totalStock') }} />
										)}
									</FormItem>
								</Col>
							</Row>
							<Row>
								<Col span={12}>
									<FormItem label='本次上架库存'  {...formItemLayout}>
										{getFieldDecorator('shelfStock', {
											rules: [{
												required: true, whitespace: true,
												validator: (rule, value, callback) => {
													if(!value){
														callback('请输入本次上架库存')
													}
													else if (parseInt(value) > parseInt(detail.totalStock)) {
														callback('不能大于总库存')
													} else {
														callback()
													}
												}
											},
											{ pattern: /^[1-9]\d*$/, message: '请输入数字' },],
											initialValue: detail.shelfStock ? detail.shelfStock : undefined
										})(
											<Input placeholder='本次上架库存数量<=总库存量' onChange={(e) => { inputChange(e.target.value, 'shelfStock') }} />
										)}
									</FormItem>
								</Col>
								<Col span={10}>
									<FormItem
										{...formItemLayoutTime}
										label="线上申请限期"
									// extra="注：同一时间，如果美的置业云首页有集团设置的弹窗广告，将只会显示集团设置的弹窗广告,生效时间最长设置时间为15天"
									>
										{getFieldDecorator('effectiveTime', {
											rules: [{ required: true, message: '请选择线上申请限期' },
											],
											initialValue: detail.startOnlineTime ? [moment(detail.startOnlineTime, 'YYYY-MM-DD HH:mm:ss'), moment(detail.endOnlineTime, 'YYYY-MM-DD HH:mm:ss')] : [],
										})(

											<RangePicker
												style={{ width: "100%" }}
												// disabled={actionType == 'detail'} 
												showTime={{
													hideDisabledOptions: true,
													defaultValue: [moment(null, 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],

												}}
												//   ranges={{ "今天后几分钟": [moment().add(5, 'm'), moment().add(15, 'd')], }}
												format="YYYY-MM-DD HH:mm:ss" onChange={(date, dateString) => { dateChange(date, dateString, 'onlineTime') }}
											// onOk={(date) => {
											// 	if (date[1].diff(date[0], 'days') > 15) {
											// 		detail.startOnlineTime = null
											// 		detail.endOnlineTime = null
											// 		dispatch({
											// 			type: 'updateStore',
											// 			payload: {
											// 				detail
											// 			}
											// 		})
											// 		form.resetFields(['effectiveTime'])
											// 		message.error('设置生效日期的范围最长不能超过15天', () => {
											// 		})
											// 		return false
											// 	}
											// }}
											/>

										)}
									</FormItem>
								</Col>
								<Col span={2}><Tooltip title="说明：线上申请限期是指客户在此时间段内可以通过美的置业云前端申请领取礼品。一旦超过此时间段则该礼品自动下架。"><Icon type="question-circle" className={cx('iconTip')} /></Tooltip></Col>
							</Row>
							<Row>
								<Col span={12}>
									<FormItem label='领取规则'  {...formItemLayout}>
										{getFieldDecorator('remark', {
											rules: [{
												required: true, whitespace: true, message: '最多输入9个字符', max: 9
											}],
											initialValue: detail.remark ? detail.remark + '' : undefined
										})(
											<Input
												// disabled={actionType == 'detail'}
												placeholder='如：礼品有限，先到先得' onChange={(e) => { inputChange(e.target.value, 'remark') }} />
										)}
									</FormItem>
								</Col>
								<Col span={10}>
									<FormItem
										{...formItemLayoutTime}
										label="线下领取限期"
									// extra="注：同一时间，如果美的置业云首页有集团设置的弹窗广告，将只会显示集团设置的弹窗广告,生效时间最长设置时间为15天"
									>
										{getFieldDecorator('effectiveTime2', {
											rules: [{ required: true, message: '请选择线下申请限期' },
											],
											initialValue: detail.startOfflineTime ? [moment(detail.startOfflineTime, 'YYYY-MM-DD HH:mm:ss'), moment(detail.endOfflineTime, 'YYYY-MM-DD HH:mm:ss')] : [],
										})(
											<RangePicker
												// disabled={actionType == 'detail'} 
												style={{ width: "100%" }}
												showTime={{
													hideDisabledOptions: true,
													defaultValue: [moment(null, 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],

												}}
												//   ranges={{ "今天后几分钟": [moment().add(5, 'm'), moment().add(15, 'd')], }}
												format="YYYY-MM-DD HH:mm:ss" onChange={(date, dateString) => { dateChange(date, dateString, 'offlineTime') }}
												onOk={(date) => {
													if (detail.startOnlineTime > detail.startOfflineTime) {
														detail.startOfflineTime = null
														detail.endOfflineTime = null
														dispatch({
															type: 'updateStore',
															payload: {
																detail
															}
														})
														form.resetFields(['effectiveTime2'])
														message.error('线下领取时间不能比线上开始时间早,请重新选择', () => {
														})
														return false
													}
												}}
											/>

										)}
									</FormItem>
								</Col>
								<Col span={2}><Tooltip title="说明：线下领取限期是指客户在此时间段内可以线下到项目营销中心领取礼品。若超过此时间段，已申请领取该礼品领取码失效。"><Icon type="question-circle" className={cx('iconTip')} /></Tooltip></Col>
							</Row>
							<Row>
								<Col span={12}>
									<FormItem {...formItemLayout} label="上下架状态">
										{getFieldDecorator('shelfStatus', {
											initialValue: detail.shelfStatus,
											rules: [
												{ required: false, whitespace: true, message: '请选择上下架状态', type: 'boolean' },
											],
										})(
											<Radio.Group onChange={(e) => inputChange(e.target.value, 'shelfStatus')}>
												<Radio value={isShelfStatus}>上架</Radio>
												<Radio value={!isShelfStatus}>下架</Radio>
											</Radio.Group>
										)}
									</FormItem>
								</Col>
								<Col span={12}>
									<FormItem {...formItemLayout} label="每人限领数量">
										{getFieldDecorator('limitCount', {
											initialValue: detail.limitCount,
											rules: [
												{ required: true, whitespace: true, message: '请选择每人限领数量' },
											],
										})(

											<Select
												// disabled={actionType != 'add'} value={detail.parentProductId}
												onChange={(e) => inputChange(e, 'limitCount')}>
												<Option value='1'>1件</Option>
												<Option value='2'>2件</Option>
												<Option value='无限'>无限</Option>
											</Select>

										)}
									</FormItem>
								</Col>
							</Row>

						</CollapsiblePanels>
						<CollapsiblePanels title={'礼品详情'} hideUpDownBtn={true}>
							<Row>
								<Col className="col" span={24} >
									<FormItem>
										<Ueditor id="addGift"
											style={{ width: '100%', height: 900 }}
											editable={true}
											html={detail.detail || ''}
											title={detail.title || ''}
											startDate={detail.startOnlineTime || ''}
											endDate={detail.endOnlineTime || ''}
											height={500}
											isSubmit={isSubmit}
											inputChange={e => {
												dispatch({ type: `${namespace}/dealEditor`, payload: { detail: e } })
											}}
											isSubmit={
												e => { dispatch({ type: `${namespace}/updateStore`, payload: { isSubmit: e.isSubmit } }) }
											}
										/>
										{/* <Ueditor id="addGift"
											style={{ width: '100%', height: 900 }}
											// editable={actionType === 'detail' ? false : true}
											html={detail.detail || ''}
											// title={detail.title || ''}
											// startDate={detail.startDate || ''}
											// endDate={detail.endDate || ''}
											height={500}
											enableBtn={isSubmit}
											inputChange={e => {
												dispatch({ type: `${namespace}/dealEditor`, payload: { detail: e } })
											}}
											// isSubmit={
											// 	e => { dispatch({ type: `${namespace}/updateStore`, payload: { isSubmit: e.isSubmit } }) }
											// }
										/> */}
									</FormItem>

								</Col>

							</Row>
						</CollapsiblePanels>
					</div>
				</Form>


			</div>

			<Modal title={'示例图'}
				onCancel={() => { changeImgModal(false) }}
				onOk={() => { changeImgModal(false) }}
				footer={null}
				width={'80%'}
				visible={imgModal.visible}>
				<Row justify={'space-between'} align={'middle'} type={'flex'}>
					{imgModal.srcs.length == 1 &&
						<Col span={24} style={{ display: 'flex', justifyContent: 'center' }}>
							<img style={{ height: '600px' }} className={cx('demoImg')} src={imgModal.srcs[0]} alt="" />
						</Col>
					}
					{imgModal.srcs.length == 2 &&
						<Col span={24}>
							<img width={'49%'} src={imgModal.srcs[0]} alt="" />
							<img width={'49%'} className={'fr'} src={imgModal.srcs[1]} alt="" />
						</Col>
					}
				</Row>
			</Modal>

		</div>

	)
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(giftAddView))
